package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.BaseBean;
import service.ActionI;
import strts.from.FullForm;
import strts.util.XmlBean;


/**
 * Servlet转发器
 * 负责接受请求，并根据请求路径进行业务处理
 * @author ywj
 *
 */
public class ActionServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		//获取当前请求路径
		String path = this.getPath(request.getServletPath());
		System.out.println("当前请求路径为：" + path);	
		
		//根获取struts处理对象map
		Map<String, XmlBean> map = (Map<String,XmlBean>) this.getServletContext().getAttribute("struts");
		
		XmlBean xml = map.get(path);
		String beanClass = xml.getBeanClass();
		
		//将页面数据按照格式转化为Form对象
		BaseBean form = FullForm.full(beanClass, request);//页面请求Form对象
		
		String actionClassFullName = xml.getActionType();//处理的action类路径
		ActionI action=null;
		String url="";
		
		try{
			Class clazz = Class.forName(actionClassFullName);
			action = (ActionI)clazz.newInstance();//映射出处理类
			
			//业务处理，并返回页面路径
			url = action.execute(request, response, form, xml.getActionForward());//处理请求，并返回转发路径

		}catch(Exception e){
			e.printStackTrace();
			System.out.println("严重，控制器异常");
		}
		request.getRequestDispatcher(url).forward(request,response);//转发到对应的页面上
	}
	
	private String getPath(String servletPath){
		return servletPath.split("\\.")[0];
	}
	
	/**
	 * Constructor of the object.
	 */
	public ActionServlet() {
		super();
	}
	
	/**
		 * Destruction of the servlet. <br>
		 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}


	/**
		 * The doPost method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to post.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	/**
		 * Initialization of the servlet. <br>
		 *
		 * @throws ServletException if an error occurs
		 */
	public void init() throws ServletException {
		// Put your code here
	}

}
